<?php
declare (strict_types = 1);
namespace app\api\controller;

use think\Request;
use think\Exception;
use app\BaseController;

use think\facade\{Log, Db};
use think\exception\ValidateException;

use app\api\validate\{OrderValidate, MakeValidate};
use app\api\model\{Users, Goods, Order, OrderMake, OrderGroup, UserShop, GoodsGroup, Admin, OrderEvaluate, OrderEvaluateImg, OrderBack};

class OrderController extends BaseController
{
    /**
	 * 预约
	 */
    public function addMakeOrder()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(MakeValidate::class)->scene('add')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $orderModel = new OrderMake();

            $field = ['order_no', 'user_id', 'goods_id', 'techn_user_id', 'admin_id', 'techn_time_id', 'remarks', 'make_time'];
            $flag = $orderModel->add($data, $field);

            if($flag['code'] != 'ok'){
                $this->error_back($flag['msg']);
            }

            /** 实例化消息提醒 */
            $newsController = new NewsController($this->app);

            /** 公众号消息提醒 */
            $newsController->news_make($data['techn_user_id'], $data['user_id'], $flag['data']);

            $this->success_back('ok', $flag['data']);
        }
    }

    /**
	 * 取消预约
	 */
    public function cancelMake()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(MakeValidate::class)->scene('show')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $orderModel = new OrderMake();

            // 获取订单详情
            $where = ['id' => $data['order_id']];
            $info = $orderModel->getFind($where);

            if($info['code'] != 'ok'){
                $this->error_back('订单不存在');
            }

            if($info['data']->getData('status') != 1){
                $this->error_back('订单状态异常！');
            }

            $editArr = [
                'id'       => $data['order_id'],
                'status'   => 3,
                'end_time' => time(),
            ];

            $flag = OrderMake::update($editArr);

            if(!$flag){
                $this->error_back('取消失败，请稍后再试！');
            }

            $this->success_back('ok');
        }
    }

    /**
	 * 预约订单列表
	 */
    public function getOrderMakeList()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(MakeValidate::class)->scene('list')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $goodsModel = new Goods();
            $userModel  = new Users();
            $orderModel = new OrderMake();

            $where = [
                'user_id'  => $data['user_id'], 
                'admin_id' => $data['admin_id'], 
                'status'   => $data['status'],
                'del_time' => 0
            ];

            $list = $orderModel->getList($where, 1, $data['curr'], $data['limit']);

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }

            $backData = [];
            foreach($list['data'] as $k => $v){
                $goods_info = $goodsModel->getFind(['id' => $v['goods_id']]);

                if($goods_info['code'] != 'ok'){
                    continue;
                }

                $backInfo = [
                    'id'         => $v['id'],
                    'small_img'  => $goods_info['data']['small_img'],
                    'title'      => $goods_info['data']['title'],
                    'techn_name' => $userModel->getVal(['id' => $v['techn_user_id']], 'nickname')['data'],
                    'make_time'  => $v->getData('make_time')?date('Y-m-d', $v->getData('make_time')) . ' ' . $v['techn_time_id']['time_name']:'',
                ];

                $backData[] = $backInfo;
            }

            $this->success_back('ok', $backData);
        }
    }

    /**
	 * 预约订单详情
	 */
    public function getOrderMakeShow()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(MakeValidate::class)->scene('show')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $userModel  = new Users();
            $goodsModel = new Goods();
            $orderModel = new OrderMake();

            // 获取订单详情
            $where = ['id' => $data['order_id']];
            $info = $orderModel->getFind($where);

            if($info['code'] != 'ok'){
                $this->error_back($info['msg']);
            }

            $goods_info = $goodsModel->getFind(['id' => $info['data']['goods_id']])['data'];
            $user_info  = $userModel->getFind(['id' => $info['data']['techn_user_id']])['data'];
            
            $backInfo = [
                'id'          => $info['data']['id'],
                'small_img'   => $goods_info['small_img'],
                'status'      => $info['data']['status'],
                'make_time'   => $info['data']['make_time'],
                'title'       => $goods_info['title'],
                'price'       => '￥' . $goods_info['price'],
                'create_time' => $info['data']['create_time'],
                'techn_name'  => $user_info['nickname'],
                'techn_phone' => $user_info['phone'],
                'remarks'     => $info['data']['remarks']
            ];      

            $this->success_back('ok', $backInfo);
        }
    }

    /**
	 * 预约订单删除
	 */
    public function setMakeRemove()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(MakeValidate::class)->scene('show')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $orderModel = new OrderMake();
            $editArr = [
                'id'       => $data['order_id'],
                'del_time' => time(),
            ];

            $flag = OrderMake::update($editArr);

            if(!$flag){
                $this->error_back('删除失败，请稍后再试！');
            }

            $this->success_back('删除成功');
        }
    }

    /**
	 * 福利金商品购买
	 */
    public function gold_order_add()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(OrderValidate::class)->scene('gold_order_add')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $goodsModel = new Goods();
            $orderModel = new Order();

            /** 查询商品信息 */
            $goods_info = $goodsModel->getFind(['id' => $data['goods_id']]);

            if($goods_info['code'] != 'ok'){
                $this->error_back('商品不存在');
            }

            $data['status']   = 1;  /** 待付款状态 */
            $data['order_no'] = getOrderNumber('FLJ');  /** 订单号 */
            $data['pay_type'] = 3;  /** 福利金支付 */

            $field = ['order_no', 'user_id', 'admin_id', 'remarks', 'price', 'status', 'pay_type', 'goods_id', 'number'];
            $flag = $orderModel->add($data, $field);

            if($flag['code'] != 'ok'){
                $this->error_back($flag['msg']);
            }

            /** 实例化消息提醒 */
            $newsController = new NewsController($this->app);

            /** 需要支付的金额 */
            $pay_money = $data['price'];

            /** 店铺ID */
            $admin_id = $data['admin_id'];

            /** 用户店铺信息条件 */
            $shop_where = ['user_id' => $data['user_id'], 'admin_id' => $admin_id];

            /** 查询用户在该店铺的资产信息 */
            $userShopInfo   = Db::name('user_shop')->where($shop_where)->find();

            if($userShopInfo['money_gold'] < $pay_money){
                $this->error_back('余额不足');
            }

            $goods_info = Db::name('goods')->where(['id' => $data['goods_id']])->find();

            Db::startTrans(); 
            try {
                /** 减去余额 */
                $card_money_flag = Db::name('user_shop')->where($shop_where)->dec('money_gold', (int)$pay_money)->update();

                if(!$card_money_flag){
                    throw new Exception("余额扣除失败【" . $data['user_id'] . "】");
                }

                /** 订单状态更改 */
                $order_change = Db::name('order')->where(['id' => $flag['data']])->update(['status' => 2, 'pay_time' => time(), 'end_time' => time()]);

                if($order_change === false){
                    throw new Exception("更新订单状态失败：单号【" . $data['order_no'] . "】");
                }

                /** 更新商品售卖数量 */
                Db::name('goods')->where(['id' => $data['goods_id']])->inc('sell_number', (int)$data['number'])->update();


                $add_info = [
                    'order_id'        => $flag['data'],
                    'user_id'         => $data['user_id'],
                    'admin_id'        => $data['admin_id'],
                    'goods_id'        => $data['goods_id'],
                    'card_number_all' => 1,
                    'card_number'     => 1,
                    'status'          => 1,
                    'goods_type'      => 2,
                    'create_time'     => time(),
                ];

                Db::name('user_card')->insert($add_info);

                Db::commit();    
            }catch(Exception $e){
                Db::rollback();
                Log::write($e->getMessage());
                $this->error_back($e->getMessage());
            }

            /** 公众号消息提醒 */
            $newsController->news_consume($data['user_id'], $data['admin_id'], $data['goods_id'], 3, $data['price']);

            $this->success_back('ok', $flag['data']);
        }
    }

    /**
	 * 商品下单
	 */
    public function goods_order_add()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(OrderValidate::class)->scene('goods_order_add')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $goodsModel = new Goods();
            $orderModel = new Order();

            /** 查询商品信息 */
            $goods_info = $goodsModel->getFind(['id' => $data['goods_id']]);

            if($goods_info['code'] != 'ok'){
                $this->error_back('商品不存在');
            }

            /** 用户在本店购买某个商品的数量 */
            $user_goods_num = $orderModel->getNum(['goods_id' => $data['goods_id'], 'user_id' => $data['user_id'], 'admin_id' => $data['admin_id'], 'status' => 2])['data'];

            if($user_goods_num >= $goods_info['data']['quota'] && $goods_info['data']['quota'] != 0){
                $this->error_back('购买次数已满，无法购买');
            }

            $data['status']   = 1;  /** 待付款状态 */
            $data['order_no'] = getOrderNumber();  /** 订单号 */

            $field = ['order_no', 'user_id', 'admin_id', 'to_user_id', 'remarks', 'price', 'status', 'pay_type', 'goods_id', 'number'];
            $flag = $orderModel->add($data, $field);

            if($flag['code'] != 'ok'){
                $this->error_back($flag['msg']);
            }

            if($data['pay_type'] == 2){
                /** 实例化消息提醒 */
                $newsController = new NewsController($this->app);

                /** 需要支付的金额 */
                $pay_money = $data['price'];

                /** 店铺ID */
                $admin_id = $data['admin_id'];

                /** 用户店铺信息条件 */
                $shop_where = ['user_id' => $data['user_id'], 'admin_id' => $admin_id];

                /** 查询用户在该店铺的资产信息 */
                $userShopInfo   = Db::name('user_shop')->where($shop_where)->find();

                if($userShopInfo['card_money'] < $pay_money){
                    $this->error_back('余额不足');
                }

                $orderInfo  = Db::name('order')->where(['id' => $flag['data']])->find();
                $userInfo   = Db::name('users')->where(['id' => $orderInfo['user_id']])->find();
                $goods_info = Db::name('goods')->where(['id' => $orderInfo['goods_id']])->find();

                Db::startTrans(); 
                try {
                    /** 减去余额 */
                    $card_money_flag = Db::name('user_shop')->where($shop_where)->dec('card_money', (int)$pay_money)->update();

                    if(!$card_money_flag){
                        throw new Exception("余额扣除失败【" . $orderInfo['user_id'] . "】");
                    }

                    /** 写入财务记录 */
                    $card_money_fin_flag = addFin($data['user_id'], $admin_id, $flag['data'], 1, 3, '-' . $pay_money, '购买' . $goods_info['title']);

                    if($card_money_fin_flag === false){
                        throw new Exception("会员扣除余额记录添加失败【" . $data['user_id'] . "】");
                    }

                    /** 获得直购奖的ID */
                    $push_user_id = $orderInfo['to_user_id']?$orderInfo['to_user_id']:$userInfo['pid'];

                    if($push_user_id > 0){
                        /** 受益人在当前店铺的资产信息 */
                        $userPushShopInfo = Db::name('user_shop')->where(['user_id' => $push_user_id, 'admin_id' => $admin_id])->find();

                        if($userPushShopInfo && $userPushShopInfo['star_id'] > 0){
                            /** 查询受益人的直购奖比例 */
                            $push_money = Db::name('star')->where(['id' => $userPushShopInfo['star_id']])->value('bonus_ratio');

                            if($push_money > 0){
                                /** 增加受益人在当前店铺的佣金 */
                                $fst_money_flag = Db::name('user_shop')->where(['user_id' => $push_user_id, 'admin_id' => $admin_id])->inc('money', round($pay_money * $push_money, 2))->update();
                                
                                if($fst_money_flag === false){
                                    throw new Exception("更新会员佣金失败【" . $push_user_id . "】");
                                }
                                
                                /** 写入财务记录 */
                                $fst_fin_flag = addFin($push_user_id, $admin_id, $orderInfo['id'], 1, 1, '+' . round($pay_money * $push_money, 2), '消费佣金');

                                if($fst_fin_flag === false){
                                    throw new Exception("会员佣金记录添加失败【" . $push_user_id . "】");
                                }

                                /** 公众号消息提醒 */
                                $newsController->news_money($push_user_id, $data['user_id'], $orderInfo['goods_id'], round($pay_money * $push_money, 2));
                            }
                        }
                    }

                    /** 增加用户在当前店铺的总消费 */
                    $money_total_flag = Db::name('user_shop')->where(['user_id' => $orderInfo['user_id'], 'admin_id' => $admin_id])->inc('money_total', (int)$pay_money)->update();

                    if($money_total_flag === false){
                        throw new Exception("更新会员店铺总消费【" . $orderInfo['user_id'] . "】");
                    }

                    /** 更新用户在当前店铺的购买状态 */
                    if($userShopInfo['is_buy'] == 0){
                        Db::name('user_shop')->where(['user_id' => $data['user_id'], 'admin_id' => $admin_id])->update(['is_buy' => 1]);
                    }

                    /** 更新用户在当前店铺的星级 */
                    $userShopModel = new UserShop();
                    $userShopModel->setStar($orderInfo['user_id'], $admin_id);

                    /** 订单状态更改 */
                    $order_change = Db::name('order')->where(['id' => $orderInfo['id']])->update(['status' => 2, 'pay_time' => time(), 'end_time' => time()]);

                    if($order_change === false){
                        throw new Exception("更新订单状态失败：单号【" . $orderInfo['order_no'] . "】");
                    }

                    /** 更新商品售卖数量 */
                    Db::name('goods')->where(['id' => $orderInfo['goods_id']])->inc('sell_number', $orderInfo['number'])->update();


                    /** 添加次卡 */
                    if($goods_info['type'] == 3){
                        $add_info = [
                            'order_id'        => $orderInfo['id'],
                            'user_id'         => $orderInfo['user_id'],
                            'admin_id'        => $orderInfo['admin_id'],
                            'goods_id'        => $orderInfo['goods_id'],
                            'card_number_all' => $goods_info['number'],
                            'card_number'     => $goods_info['number'],
                            'status'          => 1,
                            'create_time'     => time(),
                        ];

                        Db::name('user_card')->insert($add_info);
                    }

                    Db::commit();    
                }catch(Exception $e){
                    Db::rollback();
                    Log::write($e->getMessage());
                    $this->error_back($e->getMessage());
                }

                /** 公众号消息提醒 */
                $newsController->news_consume($data['user_id'], $data['admin_id'], $data['goods_id'], 2, $data['price']);
            }

            $this->success_back('ok', $flag['data']);
        }
    }

    /**
     * 商品支付
     */
    public function pay_order()
    {
        $data = input('');

        // 验证数据
        try{
            validate(OrderValidate::class)->scene('pay_order')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userModel = new Users();
        $orderModel = new Order();
        $goodsModel = new Goods();
        $adminModel = new Admin();

        $order_info = $orderModel->where(['id' => $data['order_id']])->find();
        $user_info  = $userModel->where(['id' => $order_info['user_id']])->find();
        $goods_info  = $goodsModel->where(['id' => $order_info->getData('goods_id')])->find();
        $admin_info  = $adminModel->where(['id' => $goods_info->getData('admin_id')])->find();

        $payData['openid']    = $user_info['openid'];
        $payData['shopNo']    = $admin_info['shopNo'];
        $payData['termId']    = $admin_info['termId'];
        $payData['order_no']  = $order_info['order_no'];
        $payData['total_fee'] = $order_info['price'];
        $payData['body']      = $goods_info['title'];
        $payData['notify']    = 'notify';

        // $payController = new WxpayController();
        $payController = new LakalapayController($this->app);
        $res = $payController->pay($payData);

        if($res['code'] == 200){
            $this->success_back('操作成功', $res['sign']);
        }else{
            $this->error_back($res['return_msg']);
        } 
    }

    /**
	 * 订单列表
	 */
    public function getOrderList()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(OrderValidate::class)->scene('order_list')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $orderModel = new Order();
            $goodsModel = new Goods();

            $where[] = ['user_id', '=', $data['user_id']];
            $where[] = ['admin_id', '=', $data['admin_id']];
            $where[] = ['del_time', '=', 0];

            if($data['status']){
                $where[] = ['status', '=', $data['status']];
            }

            $list = $orderModel->getList($where, 1, $data['curr'], $data['limit']);

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }

            $backData = [];
            foreach($list['data'] as $k => $v){
                $goods_info = $goodsModel->getFind(['id' => $v['goods_id']], 'id, small_img, title, subtitile, price, price_original');

                if($goods_info['code'] != 'ok'){
                    unset($list['data'][$k]);
                    continue;
                }

                $backInfo = [
                    'id'          => $v['id'],
                    'order_no'    => $v['order_no'],
                    'price'       => $v['price'],
                    'status'      => $v->getData('status'),
                    'is_evaluate' => $v['is_evaluate'],
                    'number'      => $v['number'],
                    'create_time' => $v['create_time'],
                    'goods_info'  => $goods_info['data']
                ];

                $backData[] = $backInfo;
            }

            $this->success_back('ok', $backData);
        }
    }

    /**
	 * 订单详情
	 */
    public function getOrderShow()
    {
        $data = input('post.');

        // 验证数据
        try{
            validate(OrderValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $where[] = ['id', '=', $data['order_id']];

        
        $orderModel = new Order();
        $goodsModel = new Goods();
        
        /** 订单详细信息 */
        $info = $orderModel->getFind($where);

        if($info['code'] != 'ok'){
            $this->error_back($info['msg']);
        }

        $goods_info = $goodsModel->getFind(['id' => $info['data']['goods_id']], 'id, small_img, title, subtitile, price, price_original');

        if($goods_info['code'] != 'ok'){
            $this->error_back('商品不存在');
        }

        $backInfo = [
            'id'          => $info['data']['id'],
            'order_no'    => $info['data']['order_no'],
            'price'       => $info['data']['price'],
            'number'      => $info['data']['number'],
            'status'      => $info['data']->getData('status'),
            'is_evaluate' => $info['data']['is_evaluate'],
            'create_time' => $info['data']['create_time'],
            'pay_time'    => $info['data']['pay_time'],
            'end_time'    => $info['data']['end_time'],
            'remarks'     => $info['data']['remarks'],
            'goods_info'  => $goods_info['data']
        ];

        $this->success_back('ok', $backInfo);
    }

    /**
	 * 订单取消
	 */
    public function setOrderRemove()
    {
        $data = input('post.');

        // 验证数据
        try{
            validate(OrderValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }
        
        $orderModel = new Order();
        $flag = $orderModel->edit(['id' => $data['order_id'], 'status' => 3, 'end_time' => time()]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('ok');
    }

    /**
	 * 订单删除
	 */
    public function setOrderDel()
    {
        $data = input('post.');

        // 验证数据
        try{
            validate(OrderValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }
        
        $orderModel = new Order();
        $flag = $orderModel->edit(['id' => $data['order_id'], 'del_time' => time()]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('ok');
    }

    /**
	 * 团购商品下单
	 */
    public function group_order_add()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(OrderValidate::class)->scene('group_order_add')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $goodsModel = new Goods();
            $groupModel = new GoodsGroup();
            $orderGroupModel = new OrderGroup();

            $group_info = $groupModel->getFind(['id' => $data['group_id']]);

            if($group_info['code'] != 'ok'){
                $this->error_back('该商品已下架或不存在');
            }

            /** 用户在本店购买某个商品的数量 */
            $user_group_num = $orderGroupModel->getNum(['group_id' => $data['group_id'], 'user_id' => $data['user_id'], 'admin_id' => $data['admin_id'], 'status' => 2])['data'];

            /** 查询商品信息 */
            $goods_info = $goodsModel->getFind(['id' => $group_info['data']['goods_id']]);

            if($goods_info['code'] != 'ok'){
                $this->error_back('商品不存在');
            }

            if($user_group_num >= $goods_info['data']['quota'] && $goods_info['data']['quota'] != 0){
                $this->error_back('购买次数已满，无法购买');
            }

            if($data['chief_id']){
                /** 查询团长订单信息 */
                $chief_order_info = $orderGroupModel->getFind(['id' => $data['chief_id']]);

                if($chief_order_info['code'] != 'ok'){
                    $this->error_back('拼团已过期或不存在');
                }

                if($chief_order_info['data']['status'] != 2){
                    $this->error_back('拼团已完成或已过期');
                }

                /** 当前参团人数 */
                $chief_number_new = $orderGroupModel->getNum(['chief_id' => $data['chief_id']])['data'];

                if($chief_order_info['data']['chief_number'] - 2 < $chief_number_new){
                    $this->error_back('拼团已完成');
                }
            }

            $data['status']    = 1;  /** 待付款状态 */
            $data['price']     = $data['price'];  /** 订单价格 */
            $data['order_no']  = getOrderNumber('TG');  /** 订单号 */
            $data['wait_time'] = time() + $group_info['data']['wait_time'] * 86400;  /** 拼团等待时间 */

            $field = ['order_no', 'user_id', 'group_id', 'admin_id', 'to_user_id', 'chief_id', 'remarks', 'price', 'status', 'number', 'wait_time', 'pay_type', 'chief_number'];
            $flag = $orderGroupModel->add($data, $field);

            if($flag['code'] != 'ok'){
                $this->error_back($flag['msg']);
            }

            if($data['pay_type'] == 2){
                /** 实例化消息提醒 */
                $newsController = new NewsController($this->app);

                /** 店铺ID */
                $admin_id = $data['admin_id'];

                /** 订单ID */
                $order_id = $flag['data'];

                /** 用户店铺信息条件 */
                $shop_where = ['user_id' => $data['user_id'], 'admin_id' => $admin_id];

                /** 查询用户在该店铺的资产信息 */
                $userShopInfo   = Db::name('user_shop')->where($shop_where)->find();

                if($userShopInfo['card_money'] < $data['price']){
                    $this->error_back('余额不足', $order_id);
                }

                $orderInfo  = Db::name('order_group')->where(['id' => $order_id])->find();
                $userInfo   = Db::name('users')->where(['id' => $data['user_id']])->find();
                $group_info = Db::name('goods_group')->where(['id' => $data['group_id']])->find();
                $goods_info = Db::name('goods')->where(['id' => $group_info['goods_id']])->find();

                Db::startTrans(); 
                try {
                    /** 减去余额 */
                    $card_money_flag = Db::name('user_shop')->where($shop_where)->dec('card_money', (int)$data['price'])->update();

                    if(!$card_money_flag){
                        throw new Exception("余额扣除失败【" . $data['user_id'] . "】");
                    }

                    /** 写入财务记录 */
                    $card_money_fin_flag = addFin($data['user_id'], $admin_id, $flag['data'], 1, 3, '-' . $data['price'], '购买' . $goods_info['title']);

                    if($card_money_fin_flag === false){
                        throw new Exception("会员扣除余额记录添加失败【" . $data['user_id'] . "】");
                    }

                    /** 获得直购奖的ID */
                    $push_user_id = $orderInfo['to_user_id']?$orderInfo['to_user_id']:$userInfo['pid'];

                    if($push_user_id > 0){
                        /** 受益人在当前店铺的资产信息 */
                        $userPushShopInfo = Db::name('user_shop')->where(['user_id' => $push_user_id, 'admin_id' => $admin_id])->find();

                        if($userPushShopInfo && $userPushShopInfo['star_id'] > 0){
                            /** 查询受益人的直购奖比例 */
                            $push_money = Db::name('star')->where(['id' => $userPushShopInfo['star_id']])->value('bonus_ratio');
                            
                            if($push_money > 0){
                                /** 增加受益人在当前店铺的佣金 */
                                $fst_money_flag = Db::name('user_shop')->where(['user_id' => $push_user_id, 'admin_id' => $admin_id])->inc('money', round($orderInfo['price'] * $push_money, 2))->update();
                                
                                if($fst_money_flag === false){
                                    throw new Exception("更新会员佣金失败【" . $push_user_id . "】");
                                }
                                
                                /** 写入财务记录 */
                                $fst_fin_flag = addFin($push_user_id, $admin_id, $orderInfo['id'], 1, 1, '+' . round($orderInfo['price'] * $push_money, 2), '消费佣金');

                                if($fst_fin_flag === false){
                                    throw new Exception("会员佣金记录添加失败【" . $push_user_id . "】");
                                }

                                /** 公众号消息提醒 */
                                $newsController->news_money($push_user_id, $data['user_id'], $goods_info['id'], round($orderInfo['price'] * $push_money, 2));
                            }
                        }
                    }

                    /** 增加用户在当前店铺的总消费 */
                    $money_total_flag = Db::name('user_shop')->where(['user_id' => $orderInfo['user_id'], 'admin_id' => $admin_id])->inc('money_total', (int)$orderInfo['price'])->update();

                    if($money_total_flag === false){
                        throw new Exception("更新会员店铺总消费【" . $orderInfo['user_id'] . "】");
                    }

                    /** 更新用户在当前店铺的购买状态 */
                    if($userShopInfo['is_buy'] == 0){
                        Db::name('user_shop')->where(['user_id' => $data['user_id'], 'admin_id' => $admin_id])->update(['is_buy' => 1]);
                    }

                    /** 更新用户在当前店铺的星级 */
                    $userShopModel = new UserShop();
                    $userShopModel->setStar($orderInfo['user_id'], $admin_id);

                    /** 订单状态更改 */
                    $order_change = Db::name('order_group')->where(['id' => $order_id])->update(['status' => 2, 'pay_time' => time()]);

                    if($order_change === false){
                        throw new Exception("更新订单状态失败：单号【" . $orderInfo['order_no'] . "】");
                    }

                    /** 重新获取订单信息 */
                    $order_info_new = Db::name('order_group')->where(['id' => $order_id])->find();

                    if($order_info_new['chief_id'] != 0){
                        /** 查询团长订单信息 */
                        $chief_order = Db::name('order_group')->where(['id' => $order_info_new['chief_id']])->find();

                        /** 参团人订单ID */
                        $chief_ids = Db::name('order_group')->where(['chief_id' => $order_info_new['chief_id']])->column('id');

                        /** 拼团人数 - 团长 - 参团人数 == 0 表示拼团完成，修改参团订单状态 */
                        if($chief_order['chief_number'] - 1 - count($chief_ids) == 0){
                            $chief_ids[] = $chief_order['id'];

                            /** 拼团批量修改状态为已完成 */
                            Db::name('order_group')->where([['id', 'in', $chief_ids]])->update(['status' => 3, 'end_time' => time()]);

                            /** 更新商品售卖数量 */
                            Db::name('goods')->where(['id' => $group_info['goods_id']])->inc('sell_number', $chief_order['chief_number'])->update();

                            if($goods_info['type'] == 3){
                                $chief_order_list = Db::name('order_group')->where([['id', 'in', $chief_ids]])->select();

                                $card_add_arr = [];
                                foreach($chief_order_list as $v){
                                    $add_info = [
                                        'order_id'        => $v['id'],
                                        'user_id'         => $v['user_id'],
                                        'admin_id'        => $v['admin_id'],
                                        'goods_id'        => $goods_info['id'],
                                        'card_number_all' => $goods_info['number'],
                                        'card_number'     => $goods_info['number'],
                                        'order_type'      => 2,
                                        'status'          => 1,
                                        'create_time'     => time(),
                                    ];

                                    $card_add_arr[] = $add_info;
                                }

                                Db::name('user_card')->insertAll($card_add_arr);
                            }
                        }
                    }else if($data['chief_number'] == 1){
                        Db::name('order_group')->where(['id' => $order_id])->update(['status' => 3, 'end_time' => time()]);

                        /** 更新商品售卖数量 */
                        Db::name('goods')->where(['id' => $group_info['goods_id']])->inc('sell_number', $orderInfo['number'])->update();

                        /** 添加次卡 */
                        if($goods_info['type'] == 3){
                            $add_info = [
                                'order_id'        => $orderInfo['id'],
                                'user_id'         => $orderInfo['user_id'],
                                'admin_id'        => $orderInfo['admin_id'],
                                'goods_id'        => $group_info['goods_id'],
                                'card_number_all' => $goods_info['number'],
                                'card_number'     => $goods_info['number'],
                                'order_type'      => 2,
                                'status'          => 1,
                                'create_time'     => time(),
                            ];

                            Db::name('user_card')->insert($add_info);
                        }
                    }

                    Db::commit();    
                }catch(Exception $e){
                    Db::rollback();
                    Log::write($e->getMessage());
                    $this->error_back($e->getMessage());
                }

                /** 公众号消息提醒 */
                $newsController->news_consume($data['user_id'], $data['admin_id'], $goods_info['id'], 2, $data['price']);
            }

            $this->success_back('ok', $flag['data']);
        }
    }

    /**
     * 团购商品支付
     */
    public function pay_order_group()
    {
        $data = input('');

        // 验证数据
        try{
            validate(OrderValidate::class)->scene('pay_order_group')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userModel = new Users();
        $goodsModel = new Goods();
        $adminModel = new Admin();
        $orderGroupModel = new OrderGroup();
        $goodsGroupModel = new GoodsGroup();

        /** 查询订单信息 */
        $order_group_info = $orderGroupModel->where(['id' => $data['order_group_id']])->find();

        /** 查询下单人信息 */
        $user_info  = $userModel->where(['id' => $order_group_info['user_id']])->find();

        /** 查询团购商品信息 */
        $group_info = $goodsGroupModel->where(['id' => $order_group_info['group_id']])->find();

        /** 查询商品信息 */
        $goods_info = $goodsModel->where(['id' => $group_info['goods_id']])->find();

        $admin_info  = $adminModel->where(['id' => $goods_info->getData('admin_id')])->find();

        $payData['openid']    = $user_info['openid'];
        $payData['shopNo']    = $admin_info['shopNo'];
        $payData['termId']    = $admin_info['termId'];
        $payData['order_no']  = $order_group_info['order_no'];
        $payData['total_fee'] = $order_group_info['price'];
        $payData['body']      = $goods_info['title'];
        $payData['notify']    = 'notify_group';

        // $payController = new WxpayController();
        $payController = new LakalapayController($this->app);
        $res = $payController->pay($payData);

        if($res['code'] == 200){
            $this->success_back('操作成功', $res['sign']);
        }else{
            $this->error_back($res['return_msg']);
        } 
    }

    /** 团购退款 */
    public function group_back()
    {
        $data = input('');

        $adminModel = new Admin();
        $backModel = new OrderBack();
        $orderGroupModel = new OrderGroup();

        /** 查询订单信息 */
        $order_group_info = $orderGroupModel->where(['id' => $data['order_id']])->find();

        /** 查询店铺信息 */
        $admin_info  = $adminModel->where(['id' => $order_group_info->getData('admin_id')])->find();

        $order_back_info = $backModel->where(['order_id' => $data['order_id']])->find();
        
        /** 订单号 */
        $order_no = getOrderNumber('TK');

        if($order_back_info->isEmpty()){
            $back_add = [
                'admin_id' => $order_group_info['admin_id'],
                'order_id' => $order_group_info['id'],
                'user_id'  => $order_group_info['user_id'],
                'price'    => $order_group_info['price'],
                'order_no' => $order_no,
            ];
    
            $backModel->add($back_add);
        }else{
            if($order_back_info['status'] == 2){
                $this->success_back('退款已完成');
            }
            $backModel->edit(['id' => $order_back_info['id'], 'order_no' => $order_no]);
        }

        $payData['shopNo']    = $admin_info['shopNo'];
        $payData['termId']    = $admin_info['termId'];
        $payData['oriDate']   = date('md', $order_group_info->getData('pay_time'));
        $payData['total_fee'] = $order_group_info['price'];
        $payData['tradeNo']   = $order_group_info['tradeNo'];
        $payData['order_no']  = $order_no;
        $payData['notify']    = 'notify_group_back';

        // $payController = new WxpayController();
        $payController = new LakalapayController($this->app);
        $res = $payController->back($payData);

        if($res['code'] == 200){
            $this->success_back('操作成功', $res['sign']);
        }else{
            $this->error_back($res['return_msg']);
        }
    }

    /**
	 * 团购订单列表
	 */
    public function getOrderGroupList()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(OrderValidate::class)->scene('order_list')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $userModel = new Users();
            $goodsModel = new Goods();
            $orderModel = new OrderGroup();
            $groupModel = new GoodsGroup();

            $where[] = ['user_id', '=', $data['user_id']];
            $where[] = ['admin_id', '=', $data['admin_id']];
            $where[] = ['del_time', '=', 0];

            if($data['status']){
                $where[] = ['status', '=', $data['status']];
            }

            $list = $orderModel->getList($where, 1, $data['curr'], $data['limit'], '*', 'create_time DESC');

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }

            $backData = [];
            foreach($list['data'] as $k => $v){
                $group_info = $groupModel->getFind(['id' => $v->getData('group_id')]);

                if($group_info['code'] != 'ok'){
                    unset($k);
                    continue;
                }

                $goods_info = $goodsModel->getFind(['id' => $group_info['data']['goods_id']]);

                /** 参团人的ID */
                if($v['chief_id']){
                    $chief_user_ids = $orderModel->getCol(['chief_id' => $v['chief_id']], 'user_id')['data'];
                    $chief_user_ids[] = $orderModel->getVal(['id' => $v['chief_id']], 'user_id')['data'];
                }else{
                    $chief_user_ids = $orderModel->getCol(['chief_id' => $v['id']], 'user_id')['data'];
                    $chief_user_ids[] = $v['user_id'];
                }

                /** 头像 */
                $head_img_arr = $userModel->getCol([['id', 'in', $chief_user_ids]], 'head_img')['data'];

                $backInfo = [
                    'id'            => $v['id'],
                    'order_no'      => $v['order_no'],
                    'small_img'     => $goods_info['data']['small_img'],
                    'name'          => $goods_info['data']['title'],
                    'brief'         => $goods_info['data']['subtitile'],
                    'group_price'   => $goods_info['data']['price'],
                    'user_id'       => $v['user_id'],
                    'group_id'      => $v['group_id'],
                    'user_head_img' => $head_img_arr,
                    'order_price'   => $v['price'],
                    'chief_number'  => $v['chief_number'],
                    'number'        => $v['number'],
                    'create_time'   => $v['create_time'],
                    'wait_time'     => $v['wait_time'] - time(),
                    'status'        => $v->getData('status'),
                ];

                $backData[] = $backInfo;
            }

            $this->success_back('ok', $backData);
        }
    }

    /**
	 * 团购订单详情
	 */
    public function getOrderGroupShow()
    {
        $data = input('post.');

        // 验证数据
        try{
            validate(OrderValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userModel = new Users();
        $goodsModel = new Goods();
        $orderModel = new OrderGroup();
        $groupModel = new GoodsGroup();

        $where[] = ['id', '=', $data['order_id']];
        $info = $orderModel->getFind($where);

        if($info['code'] != 'ok'){
            $this->error_back($info['msg']);
        }

        $group_info = $groupModel->getFind(['id' => $info['data']->getData('group_id')]);

        if($group_info['code'] != 'ok'){
            $this->error_back('商品不存在');
        }

        $goods_info = $goodsModel->getFind(['id' => $group_info['data']['goods_id']]);

        /** 参团人的ID */
        if($info['data']['chief_id']){
            $chief_user_ids = $orderModel->getCol(['chief_id' => $info['data']['chief_id']], 'user_id')['data'];
            $chief_user_ids[] = $orderModel->getVal(['id' => $info['data']['chief_id']], 'user_id')['data'];
        }else{
            $chief_user_ids = $orderModel->getCol(['chief_id' => $info['data']['id']], 'user_id')['data'];
            $chief_user_ids[] = $info['data']['user_id'];
        }

        /** 参团人信息 */
        $chief_user_list = $userModel->getList([['id', 'in', $chief_user_ids]], 0, 0, 0, 'head_img, phone')['data'];

        $backInfo = [
            'id'            => $info['data']['id'],
            'order_no'      => $info['data']['order_no'],
            'small_img'     => $goods_info['data']['small_img'],
            'name'          => $goods_info['data']['title'],
            'brief'         => $goods_info['data']['subtitile'],
            'group_price'   => $goods_info['data']['price'],
            'user_id'       => $info['data']['user_id'],
            'group_id'      => $info['data']['group_id'],
            'user_head_img' => $chief_user_list,
            'order_price'   => $info['data']['price'],
            'chief_number'  => $info['data']['chief_number'],
            'number'        => $info['data']['number'],
            'is_evaluate'   => $info['data']['is_evaluate'],
            'create_time'   => $info['data']['create_time'],
            'wait_time'     => $info['data']['wait_time'],
            'pay_time'      => $info['data']['pay_time'],
            'end_time'      => $info['data']['end_time'],
            'remarks'       => $info['data']['remarks'],
            'status'        => $info['data']->getData('status'),
        ];

        $this->success_back('ok', $backInfo);
    }

    /**
	 * 团购订单取消
	 */
    public function setOrderGroupRemove()
    {
        $data = input('post.');

        // 验证数据
        try{
            validate(OrderValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }
        
        $orderModel = new OrderGroup();
        $flag = $orderModel->edit(['id' => $data['order_id'], 'status' => 4, 'end_time' => time()]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('ok');
    }

    /**
	 * 团购订单删除
	 */
    public function setOrderGroupDel()
    {
        $data = input('post.');

        // 验证数据
        try{
            validate(OrderValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }
        
        $orderModel = new OrderGroup();
        $flag = $orderModel->edit(['id' => $data['order_id'], 'del_time' => time()]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('ok');
    }

    /**
	 * 订单评价
	 */
    public function setOrderEvaluate()
    {
        $data = input('post.');

        // 验证数据
        try{
            validate(OrderValidate::class)->scene('evaluate')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }
        
        $orderModel = new Order();
        $orderGroupModel = new OrderGroup();
        $orderEvalModel = new OrderEvaluate();
        $orderEvalImgModel = new OrderEvaluateImg();

        $flag = $orderEvalModel->add(['order_id' => $data['order_id'], 'user_id' => $data['user_id'], 'order_type' => $data['order_type'], 'star' => $data['star'], 'content' => $data['content']]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        if($data['order_type'] == 1){
            $orderModel->edit(['id' => $data['order_id'], 'is_evaluate' => 1]);
        }else if($data['order_type'] == 2){
            $orderGroupModel->edit(['id' => $data['order_id'], 'is_evaluate' => 1]);
        }

        if(!isset($data['img']) || empty($data['img'])){
            $this->success_back('评价成功');
        }

        /** 图片路径 */
        $img_arr = json_decode($data['img'], true);

        $img_add_arr = [];
        foreach($img_arr as $k => $v){
            $img_info = [
                'order_evaluate_id' => $flag['data'],
                'img' => $v,
            ];

            $img_add_arr[] = $img_info;
        }

        $orderEvalImgModel->addAll($img_add_arr);

        $this->success_back('评价成功');
    }

    /**
	 * 订单评价图片上传
	 */
    public function setEvaluateImgUp()
    {
        $data['img'] = request()->file('img');

        // 验证数据
        try{
            validate(OrderValidate::class)->scene('img')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $img = fileUp($data['img'], 'evaluate');

        $this->success_back('上传成功', $img);
    }
}